package com.numberONe.controller.patientcase;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.numberONe.annotation.SystemLog;
import com.numberONe.controller.index.BaseController;
import com.numberONe.entity.CaseFormMap;
import com.numberONe.entity.PatientConstitutionResultFormMap;
import com.numberONe.entity.PatientFormMap;
import com.numberONe.entity.SeriesFormMap;
import com.numberONe.entity.UserFormMap;
import com.numberONe.mapper.CaseMapper;
import com.numberONe.mapper.PatientConstitutionResultMapper;
import com.numberONe.mapper.PatientMapper;
import com.numberONe.mapper.SeriesMapper;
import com.numberONe.plugin.PageView;
import com.numberONe.util.Common;

@Controller
@RequestMapping("/case")
public class PatientCaseController extends BaseController {
	
	private static String datetime;
	
	private static int caseNoindex=1;

	@Autowired
	private CaseMapper casemapper;
	
	@Autowired
	private SeriesMapper seriesMapper;

	@Autowired
	private PatientMapper patientMapper;
	
	@Autowired
	PatientConstitutionResultMapper patientConstitutionResultMapper;
	
	@RequestMapping("list")
	public String listUI(Model model) throws Exception {
		String[] flag = getParaValues("flag");
		model.addAttribute("res", findByRes());
		return Common.WEB_PATH + "/case/list";
	}
	
	
	@RequestMapping("findBypatient")
	public String findBypatient(Map map,HttpSession session) throws Exception {
		UserFormMap userFormMap = (UserFormMap)session.getAttribute("userSession");
		String patient_id =getParaValues("patient_id")[0];
		CaseFormMap caseFormMap =  new CaseFormMap();
		PatientConstitutionResultFormMap physicalmap = new PatientConstitutionResultFormMap();
		String roleName = patientMapper.findUserRoleName(userFormMap.getInt("id"));
		if(!"管理员".equals(roleName)){
			caseFormMap.put("where","where patient_id="+patient_id+" and doctor_id="+userFormMap.getInt("id"));
			physicalmap.put("where","where patient_id="+patient_id+" and oprator_id="+userFormMap.getInt("id"));
		}else {
			caseFormMap.put("where","where patient_id="+patient_id);
			physicalmap.put("where","where patient_id="+patient_id);
		}
		map.put("patient", patientMapper.findbyFrist("id", patient_id, PatientFormMap.class));
		List<CaseFormMap> cases = casemapper.findByWhere(caseFormMap);
		physicalmap.put("patient_id", patient_id);
		List<PatientConstitutionResultFormMap> physicals = patientConstitutionResultMapper.findByWhere(physicalmap);
		map.put("cases", cases);
		map.put("physicals", physicals);
        return Common.WEB_PATH + "/case/cases";
	}
	
	@ResponseBody
	@RequestMapping("findByPage")
	public PageView findByPage( String pageNow,
			String pageSize,String column,String sort,HttpSession session,HttpServletRequest req) throws Exception {
		CaseFormMap caseFormMap = getFormMap(CaseFormMap.class);
		String prescription_date = caseFormMap.getStr("prescription_date");
		if(prescription_date==null||"".equals(prescription_date)) {
		}else {
			String[] dates = prescription_date.split(" - ");
			caseFormMap.put("begindate", dates[0]);
			caseFormMap.put("enddate", dates[1]);
		}
		UserFormMap userFormMap = (UserFormMap)session.getAttribute("userSession");
		String roleName = patientMapper.findUserRoleName(userFormMap.getInt("id"));
		if(!"管理员".equals(roleName)){
			caseFormMap.set("doctor_id",userFormMap.getInt("id"));
		}
		caseFormMap=toFormMap(caseFormMap, pageNow, pageSize,caseFormMap.getStr("orderby"));
		caseFormMap.put("column", column);
		caseFormMap.put("sort", sort);
        pageView.setRecords(casemapper.findByPage(caseFormMap));//不调用默认分页,调用自已的mapper中findPatientPage
        return pageView;
	}

	@RequestMapping(value = "/create")
	public String create(Model model, HttpSession session, @RequestParam(value = "patient_id") String patient_id,
			@RequestParam(value = "symptoms") String symptoms, @RequestParam(value = "type_no") String series) throws Exception {
		symptoms = URLDecoder.decode(symptoms, "UTF-8"); 
		PatientFormMap patient = new PatientFormMap();
		if (Common.isNotEmpty(patient_id)) {
			patient= patientMapper.findbyFrist("id", patient_id, PatientFormMap.class);
		}
		List<SeriesFormMap> typelist = new ArrayList<SeriesFormMap>();
		if (Common.isNotEmpty(series)) {
			series = series.replace(",", "','");
			typelist = seriesMapper.findByAttribute("pno", series, SeriesFormMap.class);
		}
		String type_no = "";
		for (SeriesFormMap type : typelist) {
			if(type_no=="") {
				type_no += "'"+type.getStr("no")+"'";
			}else {
				type_no += ",'"+type.getStr("no")+"'";
			}
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("type_no", type_no);
		map.put("symptoms", "'"+symptoms.replace(",","','")+"'");
		SeriesFormMap series1 = seriesMapper.findSeriesBySymptom(map).get(0);
		SeriesFormMap fseies = seriesMapper.findByAttribute("no", series1.getStr("no").substring(0, 8), SeriesFormMap.class).get(0);
		UserFormMap userFormMap = (UserFormMap)session.getAttribute("userSession");
		CaseFormMap casemap = new CaseFormMap();
		SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		casemap.put("create_date", dt.format(new Date()));
		casemap.put("case_no", createcaseNo());
		casemap.put("patient", patient);
		casemap.put("user", userFormMap);
		casemap.put("diagnosis", series1);
		casemap.put("series", fseies);
		casemap.put("symptoms", symptoms);
		model.addAttribute("casemap", casemap);
		return Common.WEB_PATH + "/case/create";
	}
	
	@ResponseBody
	@RequestMapping("addEntity")
	@SystemLog(module="诊疗管理",methods="诊疗管理-新增病历")//凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String addEntity(Model model) throws Exception{
		CaseFormMap caseFromMap = getFormMap(CaseFormMap.class);
		SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		caseFromMap.set("prescription_date", dt.format(new Date()));
		casemapper.addEntity(caseFromMap);//新增后返回新增信息
		model.addAttribute("caseFromMap", caseFromMap);
		return "success";
	}
	
	@RequestMapping("/print")
	public String print(Model model) {
		CaseFormMap caseFromMap = getFormMap(CaseFormMap.class);
		if(caseFromMap.getStr("type")!=null) {
			model.addAttribute("caseFromMap", casemapper.findBycaseNo(caseFromMap).get(0));
		}else {
			SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			caseFromMap.set("prescription_date", dt.format(new Date()));
			model.addAttribute("caseFromMap", caseFromMap);
		}
		return Common.WEB_PATH + "/case/print";
	}
	
	
	private static String createcaseNo() {
		SimpleDateFormat dt1 = new SimpleDateFormat("yyyyMMddHHmm");
		String dateString = dt1.format(new Date()); 
		if(datetime==null) {
			datetime = dateString;
			caseNoindex = 1;
		}else {
			if(!dateString.equals(datetime)) {
				datetime = dateString;
				caseNoindex = 1;
			}
		}
		String substr = ((10000+(caseNoindex++))+"").substring(1);
		return datetime+substr;
	}

}
